USE [MonkeyWarranty]
GO

/****** Object:  StoredProcedure [dbo].[InstantTicket_CopyToWarrantyTicket]    Script Date: 10/24/2013 1:39:33 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- 2013-10-23: hien created
-- =============================================
ALTER PROCEDURE [dbo].[InstantTicket_CopyToWarrantyTicket]
	@instantTicketId bigint
AS
BEGIN
	SET NOCOUNT ON;

	declare @warrantyTicketId bigint;
    
	-- warranty ticket
	insert into WarrantyTickets(Code, CreatedDate, CreatedEmployeeId, CustomerId, TicketContent, Distance, StatusId, DeliveryDate, ReceivedFrom)
	(
		select '', GetDate(), i.CreatedEmployeeId, i.CustomerId, i.TicketContent, i.Distance, 1, 
			DATEADD(day, 7, GetDate()), i.CreatedEmployeeId
		from InstantTickets i where id=@instantTicketId
	);

	set @warrantyTicketId = @@IDENTITY;
	
	update WarrantyTickets
	set Code = (SELECT RIGHT('00000' + CAST(@warrantyTicketId AS NVARCHAR), 5))
	where Id = @warrantyTicketId;

	-- products
	insert into WarrantyTickets_Products(WarrantyTicketId, ProductId, Model, ManufacturerId, 
		Serial, Quantity, WarrantyTypeId, ErrorId,
		[Description], WarrantyDate, SupplierId, 
		Note, WarrantyProductStatusId, CreatedDate)
	(
		select @warrantyTicketId, ip.ProductId, ip.Model, ip.ManufacturerId, 
			ip.Serial, ip.Quantity, ip.WarrantyTypeId, ip.ErrorId,
			ip.Description, ip.WarrantyDate, ip.SupplierId, 
			ip.Note, 1, GetDate()
		from InstantTickets_Products ip
		where InstantTicketId = @instantTicketId
	);

	select @warrantyTicketId as WarrantyTicketId;
END

GO


